﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace FundSms.SmsLib
{
    public class SerializeHelper
    {
        /// <summary>
        /// 将对象二进制序列化为字符窜
        /// </summary>
        /// <param name="o">可序列化对象</param>
        /// <returns>二进制字符窜</returns>
        public static string SerializeString(object o)
        {
            BinaryFormatter bFormatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            bFormatter.Serialize(stream, o);
            stream.Seek(0, SeekOrigin.Begin);

            StreamReader sr = new StreamReader(stream);
            string result = sr.ReadToEnd();
            sr.Close();
            stream.Close();

            return result;
        }

        /// <summary>
        /// 将字符窜数据反序列化为对象
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static object UnSerializeString(string str)
        {
            BinaryFormatter bFormatter = new BinaryFormatter();

            MemoryStream stream = new MemoryStream();
            StreamWriter sw = new StreamWriter(stream);
            sw.Write(str);
            sw.Close();
            stream.Seek(0, SeekOrigin.Begin);

            return bFormatter.Deserialize(stream);            
        }
    }
}
